package com.yx.outSourcing.controller;

import com.yx.outSourcing.R.Result;
import com.yx.outSourcing.entity.vo.OutsourcingPersonVO;
import com.yx.outSourcing.utils.ExcelUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/api/excel")
@Api(tags = "Excel导入导出")
public class ExcelController {

    @PostMapping(value = "/export", produces = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
    @ApiOperation("导出Excel数据")
    public void exportExcel(@RequestBody List<OutsourcingPersonVO> data,
                            HttpServletResponse response) {
        try {
            if (data == null || data.isEmpty()) {
                response.setStatus(HttpStatus.BAD_REQUEST.value());
                response.setContentType("text/plain;charset=UTF-8");
                response.getWriter().write("导出数据不能为空");
                return;
            }

            // 设置响应头
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Content-Disposition", "attachment;filename=outsourcing_persons.xlsx");
            response.setCharacterEncoding("UTF-8");

            try (OutputStream outputStream = response.getOutputStream()) {
                ExcelUtil.exportExcel(data, OutsourcingPersonVO.class, outputStream);
                log.info("Excel导出成功: 数据条数 = {}", data.size());
            }
        } catch (Exception e) {
            log.error("导出Excel失败", e);
            try {
                response.reset(); // ⭐关键：清空响应，避免写入部分错误内容
                response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
                response.setContentType("text/plain;charset=UTF-8");
                response.getWriter().write("导出Excel失败: " + e.getMessage());
            } catch (IOException ex) {
                log.error("写入错误信息失败", ex);
            }
        }

    }


    @PostMapping("/import")
    @ApiOperation("导入Excel数据")
    public Result<List<OutsourcingPersonVO>> importExcel(@RequestParam("file") MultipartFile file) {
        try {
            List<OutsourcingPersonVO> data = ExcelUtil.importExcel(file, OutsourcingPersonVO.class);
            return Result.success(data);
        } catch (Exception e) {
            log.error("导入Excel失败", e);
            return Result.error("导入失败: " + e.getMessage());
        }
    }
}
